package grabana

import (
	
	
	
	
	
	
	
)

// ErrFolderNotFound is returned when the given folder can not be found.
var ErrFolderNotFound = errors.New("folder not found")

// Folder represents a dashboard folder.
// See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/
type Folder struct {
	ID        uint   `json:"id"`
	UID       string `json:"uid"`
	ParentUID string `json:"parentUid"`
	Title     string `json:"title"`
}

// FindOrCreateFolder returns the folder by its name or creates it if it doesn't exist.
func ( *Client) ( context.Context,  string) (*Folder, error) {
	,  := .GetFolderByTitle(, )
	if  != nil && !errors.Is(, ErrFolderNotFound) {
		return nil, fmt.Errorf("could not find or create folder: %w", )
	}
	if  == nil {
		,  = .CreateFolder(, )
		if  != nil {
			return nil, fmt.Errorf("could not find create folder: %w", )
		}
	}

	return , nil
}

// CreateFolder creates a dashboard folder.
// See https://grafana.com/docs/grafana/latest/reference/dashboard_folders/
func ( *Client) ( context.Context,  string) (*Folder, error) {
	,  := json.Marshal(struct {
		 string `json:"title"`
	}{
		: ,
	})
	if  != nil {
		return nil, 
	}

	,  := .sendJSON(, http.MethodPost, "/api/folders", )
	if  != nil {
		return nil, 
	}

	defer func() { _ = .Body.Close() }()

	if .StatusCode != http.StatusOK {
		return nil, .httpError()
	}

	var  Folder
	if  := decodeJSON(.Body, &);  != nil {
		return nil, 
	}

	return &, nil
}

// GetFolderByTitle finds a folder, given its title.
func ( *Client) ( context.Context,  string) (*Folder, error) {
	,  := .get(, fmt.Sprintf("/api/search?type=dash-folder&query=%s", url.QueryEscape()))
	if  != nil {
		return nil, 
	}

	defer func() { _ = .Body.Close() }()

	if .StatusCode != http.StatusOK {
		return nil, .httpError()
	}

	var  []Folder
	if  := decodeJSON(.Body, &);  != nil {
		return nil, 
	}

	for  := range  {
		if strings.EqualFold([].Title, ) {
			return &[], nil
		}
	}

	return nil, ErrFolderNotFound
}